//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using OpenLS.Core.Formatting;

namespace OpenLS.Core
{
    public class GeneralFormat: Format
    {
        internal GeneralFormat(): base ("General")
        {

        }
        public override object GetFormattedValue(object o, IFormatValueConverter converter)
        {
            if (!CanFormat(o))
                Debug.WriteLine("warning, can't format " + o);
            if (o == null)
                return "";
            if (o is bool)
            {
                return BooleanToString((bool)o);
            }
            return o.ToString();
        }
        public override bool CanFormat(object o)
        {
            if (o == null)
                return true;
            if (o is bool)
                return true;
            if (o is string)
                return true;
            if (o is double)
                return true;
            if (o is int)
                return true;
            return false;
        }

        internal override void Analyze(List<FormatToken> list)
        {
            
        }

        public override FormatCategory Category
        {
            get { return FormatCategory.General; }
        }

        public object GetFormattedValue(object value, int maxCount)
        {
            if (value is double)
            {
                double dbl = (double)value;
                string s = dbl.ToString();
                int minLength = s.Length;
                if (s.Length <= maxCount)
                    return s;
                for (int i = maxCount; i >= 0; i--)
                {
                    string ss = dbl.ToString("G" + i);
                    if (ss.Length <= maxCount)
                        return ss;
                    if (ss.Length < minLength)
                    {
                        minLength = Math.Min(ss.Length, minLength);
                        s = ss;
                    }
                }
                return s;
            }
            return GetFormattedValue(value);
        }
    }
}
